//
//  NSDictionary+StringFormat.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/15.
//

#import "NSDictionary+StringFormat.h"

@implementation NSDictionary (StringFormat)
- (NSString *)dictionaryToBase64 {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: self options:0 error:&error];
    
    if (!jsonData) {
        NSLog(@"字典转Base64失败: %@", error.localizedDescription);
        return nil;
    }
    
    return [jsonData base64EncodedStringWithOptions:0];
}

- (NSString *)dicToURLQueryStr {
    NSMutableArray<NSString *> *queryItems = [NSMutableArray array];
    
    [self enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
        NSString *stringValue = [NSString stringWithFormat:@"%@", value];
        NSString *encodedKey = [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSString *encodedValue = [stringValue stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [queryItems addObject:[NSString stringWithFormat:@"%@=%@", encodedKey, encodedValue]];
    }];
    
    [queryItems sortUsingSelector:@selector(compare:)];
    return [queryItems componentsJoinedByString:@"&"];
}

@end
